package org.magnerfuller.imtoolkit.server.connection.handler;

import org.magnerfuller.imtoolkit.server.connection.event.ConnectionEvent;
import org.magnerfuller.imtoolkit.server.session.medium.SessionDescription;
import org.magnerfuller.imtoolkit.server.session.medium.SocketSessionMedium;

import java.net.*;
import java.util.Map;

import java.io.IOException;

/**
 * 
 * Class SocketConnectionHandler
 * 
 * Objects of this class handle connections on TCP/IP server sockets.
 *
 */
public class SocketConnectionHandler extends ConnectionHandler {

  /** moduleName -- the name with which this class is associated */
  public static final String moduleName = "socket";
  
  /** listenSocket -- the socket for listening */
  private ServerSocket listenSocket;

  /**
   * Constructor
   */
  public SocketConnectionHandler() throws IOException {
    super();
    listenSocket = new ServerSocket();
  }//SocketConnectionHandler

  /**
   * initialize
   */
  public void initialize(Map<String, String> params) throws Exception {
    listenSocket.bind(new InetSocketAddress(Integer.parseInt(params.get("port"))));
  }//initialize

  /**
   * run
   */
  public void run() {
    
    Socket freshSocket = null;

    while(true) {
      try {
        freshSocket = listenSocket.accept();

        // Deliver the event to listeners.
        SessionDescription sessionDesc = 
          new SessionDescription(new SocketSessionMedium(freshSocket));
        fireConnectionEvent(new ConnectionEvent(this, sessionDesc));
      }
      catch(SecurityException e) {
        System.err.println("SocketConnectionHandler::accept Security error: "
            + e);
      }
      catch(SocketTimeoutException e) {
        System.err.println("SocketConnectionHandler::accept Timeout error: "
            + e);
      }
      catch(IOException e) {
        System.err.println("SocketConnectionHandler::accept I/O error:" + e);
      }
      catch(Exception e) {
        System.err.println("SocketConnectionHandler::accept Unknown error: "
            + e);
        e.printStackTrace();
      }
    }
  }//run
  
}//SocketConnectionHandler